import md5 from 'js-md5'
import decryptData from '@/common/js/decryptData.js'
// 在文件顶部添加
let lastLoginAlertTime = 0
const LOGIN_ALERT_DEBOUNCE_TIME = 3000 // 3秒内不重复弹框
/**
 * 签名生成函数
 * @param {Object} params 请求参数
 * @param {String} secret 密钥
 * @returns {Object} 带签名的请求参数
 */
const generateSign = (params, secret) => {
  // 1. 添加时间戳和随机字符串
  const timestamp = Date.now().toString()
  const nonce = Math.random().toString(36).substr(2, 15)

  // 2. 合并参数
  const signParams = {
    ...params,
    timestamp,
    nonce
  }

  // 3. 按key升序排序
  const keys = Object.keys(signParams).sort()
  const sortedParams = {}
  keys.forEach(key => {
    sortedParams[key] = signParams[key]
  })

  // 4. 拼接参数字符串
  // let paramStr = ''
  // for (const key in sortedParams) {
  //   if (sortedParams.hasOwnProperty(key)) {
  //     let value = sortedParams[key]
  //     paramStr += `${key}=${value}&`
  //   }
  // }
  // paramStr = paramStr.slice(0, -1) // 移除最后一个&
  // console.log('res==> ', vk.myfn.httpBuildQuery(sortedParams))
  // 5. 拼接密钥
  const stringSignTemp = vk.myfn.httpBuildQuery(sortedParams) + secret

  // 6. MD5加密
  const sign = md5(stringSignTemp).toUpperCase()

  // 7. 返回带签名的参数
  return {
    ...sortedParams,
    sign
  }
}

const install = () => {
  uni.$u.http.interceptor.request = config => {
    // 获取设备信息
    const systemInfo = uni.getSystemInfoSync()
    config.header['device-id'] = systemInfo.deviceId
    config.header['platform'] = systemInfo.platform

    config.header['version'] = systemInfo.appWgtVersion || '1.0.0'

    config.header['server'] = 'true'
    config.header['accept'] = 'application/json'
    config.header['content-type'] = 'application/json'
    let token = uni.vk.getStorageSync('uni_id_token')
    if (token) {
      config.header['ba-user-token'] = `${token}`
    }

    // 生成签名参数
    const API_SECRET = 'jOxFFqMWlrtLbFKyiRBKTljGjj7Uy19J' // 实际项目中应从配置或安全存储中获取
    const signData = generateSign(
      {
        ...config.header,
        ...config.data
      },
      API_SECRET
    )
    config.header['sign'] = signData.sign
    config.header['timestamp'] = signData.timestamp
    config.header['nonce'] = signData.nonce
    // #ifndef H5
    config.header['user-agent'] = systemInfo.ua
    // #endif

    return config
  }
  uni.$u.http.interceptor.response = (res, header) => {
    if (header['Content-Encrypted'] || header['content-encrypted']) {
      const plaintext = decryptData(res, 'f1b3c9b4b8f5dc7db0e2847d8e8d6e8b')
      // console.log('解密结果:', plaintext)
      if (plaintext.code == 409) {
        const now = Date.now()
        if (now - lastLoginAlertTime < LOGIN_ALERT_DEBOUNCE_TIME) {
          return
        }
        lastLoginAlertTime = now
        vk.alert('登录过期，请重新登录', () => {
          vk.myfn.login()
        })
        return
      }
      if (plaintext.code == 303) {
        vk.myfn.login()
      }

      return plaintext
    } else {
      if (res.code == 409) {
        const now = Date.now()
        if (now - lastLoginAlertTime < LOGIN_ALERT_DEBOUNCE_TIME) {
          return
        }
        lastLoginAlertTime = now
        vk.alert('登录过期，请重新登录', () => {
          vk.myfn.login()
        })
        return
      }
      if (res.code == 303) {
        vk.myfn.login()
      }

      return res
    }
  }
}
export default install
